package com.cloudkinto.service.order.delayTask;

import cn.hutool.core.collection.CollUtil;
import com.cloudkinto.common.constant.SysConstant;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * vdf创建面单后获取的延时任务，为了避免系统重启
 *
 * @author long
 */
@Component
@Order(1)
@RequiredArgsConstructor
public class DelayTaskStartupRunner implements ApplicationRunner {

    private final DelayTaskService taskService;

    private final RedisTemplate redisTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List values = redisTemplate.opsForHash().values(SysConstant.VDF_SHIPPING_LABEL_DELAY_KEY);
        if (CollUtil.isEmpty(values)) {
            return;
        }
        for (Object value : values) {
            if (value instanceof GetShippingLabelDelay) {
                GetShippingLabelDelay labelDelay = (GetShippingLabelDelay) value;
                LocalDateTime add = labelDelay.getAddTime();
                LocalDateTime expireTime = add.plusMinutes(SysConstant.VDF_SHIPPING_LABEL_DELAY_TIME);
                LocalDateTime now = LocalDateTime.now();
                if (expireTime.isBefore(now)) {
                    // 已经过期，则加入延迟队列
                    taskService.addTask(new GetShippingLabelDelay(
                            0L,
                            labelDelay.getDataMap(),
                            labelDelay.getTaskTimeStamp(),
                            LocalDateTime.now()
                    ));
                } else {
                    // 还没过期，则加入延迟队列
                    long delay = ChronoUnit.MILLIS.between(now, expireTime);
                    taskService.addTask(new GetShippingLabelDelay(
                            delay,
                            labelDelay.getDataMap(),
                            labelDelay.getTaskTimeStamp(),
                            LocalDateTime.now()
                    ));
                }
            }
        }
    }
}

